package week259

type DetectSquares struct {
	table map[int]map[int]int
}

func Constructor() DetectSquares {
	return DetectSquares{
		table: map[int]map[int]int{},
	}
}

func (this *DetectSquares) Add(point []int) {
	x, y := point[0], point[1]

	if _, ok1 := this.table[x]; ok1 {
		if _, ok2 := this.table[x][y]; ok2 {
			this.table[x][y]++
		} else {
			this.table[x][y] = 1
		}
	} else {
		this.table[x] = map[int]int{}
		this.table[x][y] = 1
	}
}

func (this *DetectSquares) Count(point []int) int {
	x, y := point[0], point[1]

	res := 0

	if yMap, ok := this.table[x]; ok {
		for y1 := range yMap {
			if y1 == y {
				continue
			}

			var distance int
			distance = y1 - y
			if distance < 0 {
				distance = -distance
			}

			// 左边
			if _, ok1 := this.table[x-distance]; ok1 {
				countY2, ok2 := this.table[x-distance][y]  // 传入点的左边的个数
				countY3, ok3 := this.table[x-distance][y1] // 与传入点同一个纵轴的左边的个数

				if ok2 && ok3 {
					res += this.table[x][y1] * countY2 * countY3
				}

			}

			// 右边
			if _, ok1 := this.table[x+distance]; ok1 {
				countY2, ok2 := this.table[x+distance][y]  // 传入点的右边的个数
				countY3, ok3 := this.table[x+distance][y1] // 与传入点同一个纵轴的右边的个数

				if ok2 && ok3 {
					res += this.table[x][y1] * countY2 * countY3
				}

			}

		}
	}

	return res
}
